/*
 * DA4.c
 *
 * Created: 2014/3/27 1:40:31
 *  Author: Rong Xue
 In this assignment we are required to wrote the C program to controll the RGB LED by 
 the PWM method. 
 */ 

// include libraries
#define F_CPU 1000000L // 1MHz
#include <util/delay.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <inttypes.h>

uint8_t a=0; //variables for the interrupt frequencies
uint8_t b=0;
uint8_t c=0;


int main(void)
{
	sei(); // enable interrupt
	PORTB=0x00; // Turn all LEDs off
	DDRB |=1<<PB3; 
	DDRD |=(1<<PD5)|(1<<PD6); //set output toggling pin for RGB LED
	
	// allow timer0, timer1, timer2 interrupt
	TIMSK0 = (1<<TOIE0); 
	TIMSK1 = (1<<TOIE1);
	TIMSK2 = (1<<TOIE2);
	
	// 25 = %10of 255
	TCNT0 = 25;
	TCNT1L = 25;
	TCNT2 = 25;
	
	// setup the timer mode the  
	TCCR0A = (1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
	TCCR0B = (1<<CS00);
	TCCR1A = (1<<WGM10)|(1<<COM1A1);
	TCCR1B = (1<<CS10)|(WGM12);
	TCCR2A = (1<<WGM21)|(1<<WGM21)|(1<<COM2A1);
	TCCR2B = (1<<CS20); 
	
    while(1)
    {
    for (int x=0; x!=(230-a); x++){ //loop which turns on the LED
	OCR0A=OCR1A=OCR2A=x+25;
	_delay_ms(10); //10ms delay function
    }
	for (int y=(230-a);y>0;y--){ // loop which turn off the LED
	OCR0A=OCR1A=OCR2A=y+25; //10ms delay function
	_delay_ms(10);
	}		
}return 0;
	}


ISR(TIMER0_OVF_vect){ //interrupt change the period for color change	
	a++;
	TCNT0=a+25;
	if (TCNT0==230)
	a=0;
	sei();
	}
	
ISR(TIMER1_OVF_vect){//interrupt change the period for color change	
	if(c>200)
	b++;
	TCNT1L=b+25;
	if(TCNT1L==230)
	b=0;
	sei();
	}
ISR(TIMER2_OVF_vect){//interrupt change the period for color change	
	if(b>200)
	c++;
	TCNT2=c+25;
	if(TCNT2==230)
	c=0;
	sei();
	}
	
	
	